package src.linkeLlist;

public class no19 {
    //删除链表的倒数第 n 个结点
    public static void main(String[] args) {

    }

    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode dummy = new ListNode();
        dummy.next = head;
        ListNode p = dummy;  //p快指针，q慢指针，p先走n+1步，p、q再同时后移，p指向null时，q指向待删node的前一个
        ListNode q = dummy;
        n = n + 1;
        while (n > 0 && p != null) {
            p = p.next;
            n--;
        }
        while (p != null) {
            p = p.next;
            q = q.next;
        }  //此时q指向待删node的前一个node

        q.next = q.next.next;
        return dummy.next;

    }
}
